package com.mock.ems.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.mock.base.util.CollectionUtil;
import com.mock.base.util.DateUtil;
import com.mock.base.util.NumberUtil;
import com.mock.base.util.StringUtil;
import com.mock.ems.common.JsonResult;
import com.mock.ems.config.UserManager;
import com.mock.ems.utils.TGlCateUtil;

import java.util.*;

/**
 * Created by MOCK on 2017/8/26.
 */
public class MallItemController extends Controller {

    public void index() {
        renderJsp("/page/mallitem/mallitem_list.jsp");
    }

    public void pagination() {

        int pageNumber = getParaToInt("pageNumber");
        int pageSize = getParaToInt("pageSize");

        String selectSQL = "select a.*,b.party_id_,b.store_name_,b.contact_ ";
        StringBuilder exceptSelectSQL = new StringBuilder(" from t_prod_entity a inner join t_ou_shop b " +
                " on a.shop_id_ = b.id_ where 1 = 1");
        List<Object> params = new ArrayList<Object>();

        String nickName = getPara("nickName");
        if (StringUtil.isNotEmpty(nickName)) {
            Record userRecord = Db.findFirst("select id from user where nick_name like ? ",'%' + nickName + '%');
            if (null != userRecord) {
                exceptSelectSQL.append(" and b.party_id_ = ?");
                params.add(userRecord.getLong("id"));
            }
        }

        String storeName = getPara("store_name_");
        if (StringUtil.isNotEmpty(storeName)) {
            exceptSelectSQL.append(" and b.store_name_ like ?");
            params.add("%" + storeName.trim() + "%");
        }

        String phone = getPara("phone");
        if (StringUtil.isNotEmpty(phone)) {
            exceptSelectSQL.append(" and b.contact_ like ?");
            params.add("%" + phone.trim() + "%");
        }

        String status = getPara("status_");
        if (StringUtil.isNotEmpty(status)) {
            exceptSelectSQL.append(" and a.status_ = ?");
            params.add(status);
        }


        Date begin_time = DateUtil.parseToDate(getPara("begin_time"),DateUtil.FULL_PATTERN);
        Date end_time = DateUtil.parseToDate(getPara("end_time"),DateUtil.FULL_PATTERN);

        if (null != begin_time && end_time == null) {
            exceptSelectSQL.append(" and a.create_time_ >= ? ");
            params.add(begin_time);
        }

        if (null == begin_time && end_time != null) {
            exceptSelectSQL.append(" and a.create_time_ <= ? ");
            params.add(end_time);
        }

        if (null != begin_time && null != end_time) {
            exceptSelectSQL.append(" and a.create_time_ >= ? and a.create_time_ <= ? ");
            params.add(begin_time);
            params.add(end_time);
        }
        exceptSelectSQL.append(" order by a.update_time_ desc ");
        Page<Record> recordList = null;
        if (params.size() == 0) {
            recordList = Db.paginate(pageNumber, pageSize, selectSQL, exceptSelectSQL.toString());
        }else {
            recordList = Db.paginate(pageNumber, pageSize, selectSQL, exceptSelectSQL.toString(),params.toArray());
        }

        if (CollectionUtil.isNotEmpty(recordList.getList())) {
            recordList.getList().forEach(item -> {
                Long userId = NumberUtil.toLong(item.get("party_id_"));
                Record user = UserManager.getUser(userId);
                if(user == null){
                    user = Db.findById("user",userId);
                    if(user != null){
                        UserManager.setUser(user);
                    }
                }
                item.set("nick_name",user == null ? "未知" : user.get("nick_name"));

                Record recommend = Db.findFirst("select id_ from t_prod_rec where rec_id_ = ? and src_type_ = ?"
                        ,item.getStr("id_"),"indexProduct");
                if(recommend != null){
                    item.set("recommend","Y");
                }else{
                    item.set("recommend","N");
                }
            });
        }

        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put("total", recordList.getTotalRow());
        returnMap.put("rows", recordList.getList());
        renderJson(returnMap);
    }

    public void audit() {

        String id_ = getPara("id");
        Record record = Db.findById("t_prod_entity","id_",id_);

        if (null != record) {

            String shopId = record.get("shop_id_");
            Record shopRecord = Db.findById("t_ou_shop","id_",shopId);
            if (null != shopRecord) {
                String typeStr = shopRecord.get("business_type_");
                shopRecord.set("business_type_","online_store".equals(typeStr) ? "线上店" : "oto".equals(typeStr) ? "线上实体店" : "未知类型");
                record.set("shop",shopRecord.getColumns());
            }

            String mainImage = Db.queryStr("select cloud_path_ from t_prod_media where prod_id_ = ? and is_main_ = 'Y'",id_);
            record.set("mainImage",mainImage);

            List<Record> subImageList = Db.find("select cloud_path_ from t_prod_media where prod_id_ = ? and is_main_ = 'Y'",id_);
            record.set("subImageList",subImageList);

            Record sku = Db.findFirst("select * from t_sale_sku where sale_prod_id_ = ? and is_default_ = 'Y'",id_);
            record.set("sku",sku);

            Double point_proportion_ = Db.queryDouble("select point_proportion_ from t_sale_entity where sale_id_ = ?",id_);
            record.set("point_proportion_",point_proportion_);

            setAttr("record",record.getColumns());
        }
        renderJsp("/page/mallitem/mallitem_audit.jsp");
    }

    public void auditUpdate() {

        String id_ = getPara("id");
        Integer status = getParaToInt("status");
        String status_str = status == 1 ? "audit_success" : "audit_fail";
        Record record = Db.findById("t_prod_entity","id_",id_);
        record.set("status_",status_str).set("update_time_",DateUtil.getDate());
        Db.update("t_prod_entity","id_",record);

        //审核通过
        if (status == 1) {
            String pointProportion = getPara("point_proportion_");

            Record saleEntity = Db.findFirst("select * from t_sale_entity where sale_id_ = ?",id_);
            saleEntity.set("point_proportion_",pointProportion);
            Db.update("t_sale_entity","sale_id_",saleEntity);
        }

        renderJson(new JsonResult().status("000").show("操作成功"));
    }

    @Before(Tx.class)
    public void auditBatchUpdate(){
        String rowIdList = getPara("selectRowList");

        if(StringUtil.isEmpty(rowIdList)){
            renderJson(new JsonResult().status("001").show("未正确选择商品，请联系管理员"));
            return;
        }

        String[] rowIdArr = rowIdList.split(",");
        for(String id : rowIdArr){
            // 循环审核选择的记录
            Record record = Db.findById("t_prod_entity", "id_", id);
            record.set("status_","audit_success").set("update_time_",DateUtil.getDate());
            Db.update("t_prod_entity","id_", record);
        }

        renderJson(new JsonResult().status("000").show("操作成功"));
    }

    @Before(Tx.class)
    public void recommend(){

        String shopIdList = getPara("shopIdList");

        if(StringUtil.isEmpty(shopIdList)){
            renderJson(new JsonResult().status("001").show("未正确选择商品，请联系管理员"));
            return;
        }

        String[] shopIdArr = shopIdList.split(",");
        for(String id : shopIdArr){
            Record record = Db.findFirst("select id_ from t_prod_rec where rec_id_ = ? and src_type_ = ?"
                    ,id,"indexProduct");
            if(record == null){
                record = new Record();
                Long id_ = TGlCateUtil.getId();
                record.set("rec_id_",id).set("src_type_","indexProduct")
                        .set("sort_",1).set("create_time_", DateUtil.getDate()).set("id_",id_);
                Db.save("t_prod_rec","id_",record);
            }
        }

        renderJson(new JsonResult().status("000").show("推荐成功"));
    }

    @Before(Tx.class)
    public void unrecommend(){

        String shopIdList = getPara("shopIdList");

        if(StringUtil.isEmpty(shopIdList)){
            renderJson(new JsonResult().status("001").show("未正确选择商品，请联系管理员"));
            return;
        }

        String[] shopIdArr = shopIdList.split(",");
        for(String id : shopIdArr){
            Record record = Db.findFirst("select id_ from t_prod_rec where rec_id_ = ? and src_type_ = ?"
                    ,id,"indexProduct");
            if(record != null){
                Db.delete("t_prod_rec","id_",record);
            }
        }

        renderJson(new JsonResult().status("000").show("推荐成功"));
    }
}
